package com.supersystem.utils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <li>Brief: <li>Description:
 *
 * @author luoyg
 * @version
 * @see
 * @since
 */

public abstract class ExpressionUtils {
    /**
     * EL表达式匹配
     */
    private static final String EL_EXPRESS = "\\$(!?)\\{\\s*([A-z0-9_]+)\\s*\\}";

    /**
     * 正则表达式替换
     *
     * Map<String, Object> datas = new HashMap<String, Object>(); datas.put("name", "张三"); datas.put("age", 18); String
     * str = "姓名：${name},年龄：$!{age},简介：${profile},学历：$!{scientific}"; String replaceEL = replaceEL(str, datas);
     *
     * 输出结果:
     *
     * 姓名：张三,年龄：18,简介：,学历：scientific
     *
     * @param input
     * @param params
     * @return
     */
    public static String replaceEL(String input, Map<String, Object> params) {
        Pattern pattern = Pattern.compile(EL_EXPRESS);
        Matcher matcher = pattern.matcher(input);
        String result = input;
        while (matcher.find()) {
            String el = matcher.group(0);
            String c = matcher.group(1);
            String key = matcher.group(2);
            Object value = params.get(key);
            if (value != null) {
                result = result.replace(el, params.get(key).toString());
            } else if ("!".equals(c)) {
                result = result.replace(el, key);
            } else {
                result = result.replace(el, "");
            }
        }
        return result;
    }
}
